#include "modbus_app.h"

static void ModbusGetTemp(uint16_t* value);
static void ModbusGetHumi(uint16_t* value);
static void ModbusSetLed1(uint16_t value);
static void ModbusSetLed2(uint16_t value);

// mondbus从机地址
#define MODBUS_SLAVE_ADDR 0x01 
#define MODBUS_R   (1<<0)
#define MODBUS_W   (1<<1)
/**
 * @desc  : Modebus初始化
 * @date  : 2025-04-16
 * @author: AnRui
 * @note  :
 */
void ModebusAppInit() {
    // Modebus初始化配置
    ModbusSlaveInstance_t modbusSlaveInstance = { .slaveAddr = MODBUS_SLAVE_ADDR,.baudRate = 9600 };
    ModbusSlaveInit(&modbusSlaveInstance);
    // 温度数据读取 注册
    RegInstanceArrReg((MbRegisterInstance_t) { .property = MODBUS_R, .address = 0x0000, .minValue = 0, .maxValue = 0, .ReadCb = ModbusGetTemp, .WriteCb = NULL });
    // 湿度数据读取 注册
    RegInstanceArrReg((MbRegisterInstance_t) { .property = MODBUS_R, .address = 0x0001, .minValue = 0, .maxValue = 0, .ReadCb = ModbusGetHumi, .WriteCb = NULL });
    // 点亮led1 注册
    RegInstanceArrReg((MbRegisterInstance_t) { .property = MODBUS_W, .address = 0x0002, .minValue = 0, .maxValue = 1, .ReadCb = NULL, .WriteCb = ModbusSetLed1 });
    // 点亮led2 注册
    RegInstanceArrReg((MbRegisterInstance_t) { .property = MODBUS_W, .address = 0x0003, .minValue = 0, .maxValue = 1, .ReadCb = NULL, .WriteCb = ModbusSetLed2 });
}


/**
 * @desc  : modebus轮询执行
 * @date  : 2025-04-16
 * @author: AnRui
 * @note  :
 */
void ModebusAppPoll() {
    ModbusSlavePoll();
}

/**
 * @desc  : 获取温度数据
 * @date  : 2025-04-16
 * @author: AnRui
 * @param : value - {参数说明}:
 * @note  : 因为原数据是float类型 所以*10 在转成uint16_t 保证不丢失精度
 */
static void ModbusGetTemp(uint16_t* value) {
    SensorData_t sensorData;
    GetSensorData(&sensorData);
    *value = (uint16_t)(sensorData.temp * 10);
}



/**
 * @desc  : 获取湿度数据
 * @date  : 2025-04-16
 * @author: AnRui
 * @param : value - {参数说明}:
 * @note  : 因为原数据是float类型 所以*10 在转成uint16_t 保证不丢失精度
 */
static void ModbusGetHumi(uint16_t* value) {
    SensorData_t sensorData;
    GetSensorData(&sensorData);
    *value = (uint16_t)(sensorData.humi * 10);
}

/**
 * @desc  : 点亮|熄灭led1
 * @date  : 2025-04-16
 * @author: AnRui
 * @param : value - {参数说明}:
 * @note  :
 */
static void ModbusSetLed1(uint16_t value) {
    value == 0 ? TurnOffLed(LED1) : TurnOnLed(LED1);
}

/**
 * @desc  : 点亮|熄灭led2
 * @date  : 2025-04-16
 * @author: AnRui
 * @param : value - {参数说明}:
 * @note  :
 */
static void ModbusSetLed2(uint16_t value) {
    value == 0 ? TurnOffLed(LED2) : TurnOnLed(LED2);
}
